/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.customview.MarqueeTextView;
import com.shwread.android.ui.dialog.NoNetDialog;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import logic.bean.LocationBean;
import logic.constants.DefaultConsts;
import logic.lbs.MapUtils;
import logic.lbs.MyLocation;
import logic.lbs.MyLocationListener;
import logic.util.NetworkUtil;
import logic.util.ScreenUtil;
import logic.util.Util;


/**
 * 人保定位页面
 *
 * @author 刘宾
 * @date 2015年1月20日 上午9:30:29
 */
public class LocationActivity
        extends
        BaseSimpleActivity
        implements
		AMap.OnMarkerClickListener,
		AMap.OnMapLoadedListener,
        OnClickListener,
		LocationSource,
        MyLocationListener
{
	private TextView                  tvTitle, tvTopAddress;
	private ViewPager                 viewPager;
	private Button                    btnBack;
	private View                      topView;
	private Context                   mContext;

	private AMap                      aMap;
	private MapView mapView;
	private UiSettings mUiSettings;
	private ArrayList<LocationBean>   data;
	private ArrayList<Marker>         markers;
	private AMapLocation              lastLocation;
	private MyLocation                myLocation;
	private OnLocationChangedListener mListener;

	private boolean                   isFirst = true;
	private int                       currMarkerIndex;
	private QyreaderPerferencesUtil   xmlUtil;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location);
		mapView = (MapView) findViewById(R.id.location_map);
		mapView.onCreate(savedInstanceState);
		mContext = this;
		myLocation = new MyLocation(mContext, this);
		data = LocationBean.getLocationList();
		markers = new ArrayList<Marker>();
		xmlUtil = QyreaderPerferencesUtil.getInstance(this, DefaultConsts.FIRST_TAG);
		initView();
		showHelp();
	}

	private void initView() {
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText("人保网点");
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		topView = findViewById(R.id.location_top_layout);
		topView.setOnClickListener(this);
		tvTopAddress = (MarqueeTextView) findViewById(R.id.location_top_address);
		viewPager = (ViewPager) findViewById(R.id.location_viewpager);
		if (aMap == null)
		{
			aMap = mapView.getMap();
			mUiSettings = aMap.getUiSettings();
		}
		initMap();
	}

	private void initMap() {
		// 自定义系统定位小蓝点
		MyLocationStyle myLocationStyle = new MyLocationStyle();
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_default_gps));// 设置小蓝点的图标
		myLocationStyle.strokeColor(Color.parseColor("#568dbc"));// 设置圆形的边框颜色
		myLocationStyle.radiusFillColor(Color.parseColor("#306bbce2"));// 设置圆形的填充颜色
		myLocationStyle.strokeWidth(0.1f);// 设置圆形的边框粗细
		aMap.setMyLocationStyle(myLocationStyle);
		aMap.setLocationSource(this);// 设置定位监听
		aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
		aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		aMap.setOnMapTouchListener(new TouchListener());
		aMap.setMyLocationRotateAngle(90);// 设置小蓝点旋转角度
		//设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		aMap.setMyLocationEnabled(true);
		aMap.moveCamera(CameraUpdateFactory.zoomTo(MapUtils.ZOOM)); //缩放比例
		mUiSettings.setMyLocationButtonEnabled(false); //是否显示默认的定位按钮
		//设置地图是否可以手势缩放大小
		mUiSettings.setZoomGesturesEnabled(true);
		//设置地图默认的缩放按钮是否显示
		mUiSettings.setZoomControlsEnabled(false);
	}

	/** 重新标注所有的marker */
	private void resetMarkers(int position) {
		if (aMap != null)
		{
			for (Marker m : markers)
            {
	            m.remove();
            }
			addMarkersToMap(position);
		}
	}

	/**
	 * 在地图上添加marker
	 */
	private void addMarkersToMap(int position) {
		for (int i = 0; i < data.size(); i++)
		{
			int drawableId = i==position ? R.drawable.location_marker_icon : R.drawable.location_marker_red_icon ;
			Marker marker = aMap.addMarker(new MarkerOptions().position(data.get(i).latLng).title(data.get(i).name).icon(MapUtils.getIcon(mContext, drawableId, String.valueOf(i + 1))));
			marker.setObject(i);
			markers.add(marker);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
			case R.id.location_top_layout:
				if (aMap != null && lastLocation != null)
				{
					MapUtils.animMap(aMap, new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()));
				}
				break;

		}
	}

	/**
	 * 对marker标注点点击响应事件
	 */
	@Override
	public boolean onMarkerClick(final Marker marker) {
		final String str = marker.getObject().toString();
		if (Util.isNotEmpty(str) && Util.isNumeric(str))
		{
			if(currMarkerIndex != Integer.valueOf(str)){
				currMarkerIndex = Integer.valueOf(str);
				resetMarkers(currMarkerIndex);
			}
			viewPager.setCurrentItem(currMarkerIndex);
		}
//		if(marker.isInfoWindowShown()){
//			marker.hideInfoWindow();
//		}else{
//			marker.showInfoWindow();
//		}
		//true:地图不会移动，false:当前marker会移动到地图中心
		return false;
	}

	/**
	 * 监听amap地图加载成功事件回调
	 */
	@Override
	public void onMapLoaded() {
		myLocation.enableLocation(2000, 10);
		tvTopAddress.setText("正在定位...");
	}

	@Override
	public void activate(OnLocationChangedListener arg0) {
		mListener = arg0;
	}

	@Override
	public void deactivate() {
		mListener = null;
	}

	@Override
	public void locationFail() {
		isFirst = true;
		tvTopAddress.setText("定位失败,正在重新定位...");
		myLocation.enableLocation(2000, 10);
	}

	@Override
	public void locationFinish(AMapLocation location) {
		lastLocation = location;
		tvTopAddress.setText(location.getAddress().replace("浙江省", ""));
		if (mListener != null)
		{
			mListener.onLocationChanged(location);
		}
		else
		{
			MapUtils.animMap(aMap, new LatLng(location.getLatitude(), location.getLongitude()));
		}
		aMap.setMyLocationRotateAngle(aMap.getCameraPosition().bearing);

		refreshUI();
	}

	@SuppressWarnings ({
	        "unchecked",
	        "rawtypes"
	})
	private void refreshUI() {
		if (isFirst)
		{
			for (int i = 0; i < data.size(); i++)
			{
				final float value = MapUtils.calculateDistance(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()),data.get(i).latLng);
				data.get(i).distance = value;
				System.out.println(data.get(i).name + "--" + data.get(i).distance);
			}
			Collections.sort(data, new Comparator()
			{
				@Override
				public int compare(Object o1, Object o2) {
					return ((LocationBean) o1).distance.compareTo(((LocationBean) o2).distance);
				}
			});
			System.out.println("排序后：" + data.toString());
			viewPager.setOnPageChangeListener(new PagerChangeListener());
			viewPager.setAdapter(new ViewPagerAdapter());
			viewPager.setOffscreenPageLimit(3);
			viewPager.setPageMargin(ScreenUtil.dip2px(3));
			addMarkersToMap(0);
			MapUtils.animMap(aMap, data.get(0).latLng);
//			markers.get(0).showInfoWindow();
			isFirst = false;
		}
	}

	private class PagerChangeListener
	        implements
	        OnPageChangeListener
	{
		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int i) {
			if(currMarkerIndex != i){
				currMarkerIndex = i;
				resetMarkers(currMarkerIndex);
			}
			MapUtils.animMap(aMap, new LatLng(data.get(i).latLng.latitude, data.get(i).latLng.longitude));
//			markers.get(i).showInfoWindow();
		}
	}

	@SuppressLint ("UseSparseArrays")
	private HashMap<Integer, View> views = new HashMap<Integer, View>();

	public class ViewPagerAdapter
	        extends
	        PagerAdapter
	{

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container,final int position) {
			View view = views.get(position);
			if (view == null)
			{
				final LocationBean bean = data.get(position);
				view = getLayoutInflater().inflate(R.layout.location_viewpager_item, null);
				TextView tvName = (TextView) view.findViewById(R.id.location_viewpager_item_name);
				TextView tvAddress = (TextView) view.findViewById(R.id.location_viewpager_item_address);
				TextView tvPhone = (TextView) view.findViewById(R.id.location_viewpager_item_phone);

				tvName.setText((position + 1) + "、" + bean.name);
				tvAddress.setText(MapUtils.formatDistance(bean.distance)+"    "+bean.address);
				tvPhone.setText("电话：" + bean.phone);
				((ImageView) view.findViewById(R.id.location_viewpager_item_phone_img)).setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + bean.phone));
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
					}
				});
				view.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0) {
						//TODO
						if(currMarkerIndex != position){
							currMarkerIndex = position;
							resetMarkers(currMarkerIndex);
						}
						MapUtils.animMap(aMap, new LatLng(data.get(position).latLng.latitude, data.get(position).latLng.longitude));
					}
				});
				views.put(position, view);
			}
			if (view.getParent() != null)
			{
				container.removeView(view);
			}
			container.addView(view);
			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(views.get(position));
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
		myLocation.disableLocation();
	}

	private class TouchListener implements AMap.OnMapTouchListener {
		@Override
        public void onTouch(MotionEvent arg0) {
			//记录当前缩放级别
			if(arg0.getAction()==MotionEvent.ACTION_UP){
		    	MapUtils.ZOOM = aMap.getCameraPosition().zoom;
//		    	Util.showToast(mContext, "当前缩放比例："+aMap.getCameraPosition().zoom);
		    }
        }
	}

	private void showHelp() {
//		xmlUtil.setFirstLBS(true);//测试
		if (xmlUtil.isFirstLBS())
		{
			topView.setVisibility(View.INVISIBLE);
			LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.lbs_firstin, null);
			final Dialog dialog = new Dialog(this,R.style.guide_dialog);
			dialog.setContentView(view);
			dialog.setCancelable(false);
			Button closeBtn = (Button) view.findViewById(R.id.lbs_firstin_btn);
			closeBtn.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					dialog.dismiss();
					topView.setVisibility(View.VISIBLE);
					checkNetWork();
				}
			});
			dialog.show();
			xmlUtil.setFirstLBS(false);
		}else{
			checkNetWork();
		}
	}
	private void checkNetWork(){
		if(!NetworkUtil.isNetAvailable(mContext)){
			NoNetDialog netDialog = new NoNetDialog(mContext);
			netDialog.setCancelable(false);
			netDialog.show();
		}
	}
}
